package com.antilia.infomaresme.mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author Ernesto
 *
 */
public class MailUtil {
	
	public static void sendEmail(String aToEmailAddr,
			String aSubject, String aBody) throws MessagingException {
		String host = "whm12.clusterspan.net";
		String user = "admin@infomaresme.javaprovider.net";
		String pass = "Mellon11";
		String to = aToEmailAddr;
		String from = "admin@infomaresme.javaprovider.net";
		String subject = aSubject;
		String messageText = aBody;
		boolean debug = false;
		
		Properties props = System.getProperties();
		props.put("mail.host", host);
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.host", host);
		Session session = Session.getDefaultInstance(props, null);
		// create a message
		session.setDebug(debug);
		Message msg = new MimeMessage(session);
		
		try {			
			msg.setFrom(new InternetAddress(from));
			InternetAddress[] address = {new InternetAddress(to)};
			msg.setRecipients(Message.RecipientType.TO, address);
			msg.setSubject(subject);
			msg.setSentDate(new Date());
			msg.setText(messageText);
			Transport transport = session.getTransport("smtp");
			transport.connect(host, user, pass);
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
		} catch (MessagingException ex){
			System.err.println("Cannot send email. " + ex);
			ex.printStackTrace();
			throw ex;
		}
	}
}
